<?php

namespace app\admin\controller;

use think\Controller;
use think\facade\Session;
use Util\Sysdb;
use app\admin\model\Userlog as log;

class Login extends Controller
{
    //登录页面
    public function login(){
        return view();
    }

    //管理员登录
    public function dologin()
    {
        $username = trim(input('post.username'));
        $pwd = trim(input('post.pwd'));
        $verifycode = trim(input('post.verifycode'));

        if ($username == '') {
            exit(json_encode(array('code' => 1, 'msg' => '用户名不能为空')));
        }
        if ($pwd == '') {
            exit(json_encode(array('code' => 1, 'msg' => '密码不能为空')));
        }
        if ($verifycode == '') {
            exit(json_encode(array('code' => 1, 'msg' => '请输入验证码')));
        }

        //验证验证码
        if(strlen($verifycode) > 6 || strlen($verifycode) < 6){
            exit(json_encode(array('code' => 1, 'msg' => '验证码位数不对')));
        }
        if (!captcha_check($verifycode)) {
            exit(json_encode(array('code' => 1, 'msg' => '验证码错误')));
        }


        //验证用户
        $this->db = new Sysdb;
        $admin = $this->db->table('sact_admin')->where(array('username' => $username))->item();
        if (!$admin) {
            exit(json_encode(array('code' => 1, 'msg' => '用户不存在')));
        }
        if (md5($pwd) != $admin['password']) {
            exit(json_encode(array('code' => 1, 'msg' => '密码错误')));
        }
        if ($admin['status'] == 1) {
            exit(json_encode(array('code' => 1, 'msg' => '用户已被禁用')));
        }

        //设置用户session
        session('admin', $admin);
        //登陆成功写入日志
        $this->loginlog();
        exit(json_encode(array('code' => 0, 'msg' => '登陆成功')));
    }

    //退出
    public function logout()
    {
        Session::delete('admin');
        //$this->success('正在返回登录页面');
        header('location:login');
    }

    //写入日志
    public function loginlog(){
        //增加用户登录日志
        //$ip = $_SERVER["REMOTE_ADDR"];
        $server_hostname = gethostname();
        //$server_hostname .= "";//这里的点可加可不加
        $server_ip = gethostbyname($server_hostname);
        $userlog = new log();
        $userid = Session::get('admin.id');
        $nickname = Session::get('admin.username');
        $userlog->addUserlog($userid,$nickname,$server_ip,$server_hostname);
    }


}